package models

import (
	"errors"
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"go-admin/global/orm"
	"go-admin/tools"
	"strconv"
)

type VRRevisit struct {
	ZxRevisit
	OrderId    string `json:"orderId, omitempty"`
	CustomName string `json:"customName, omitempty"`
	CustomTel  string `json:"customTel, omitempty"`
	CustomAddr string `json:"customAddr, omitempty"`
}

// 获取VRRevisit
func (e *VRRevisit) GetRevisitById(revisitId string) (VRRevisit, error) {
	var doc VRRevisit
	if tools.NullStr(revisitId) {
		return doc, errors.New("SignId is empty")
	}
	selectSql := "SELECT zr.*, zo.custom_name, zo.custom_tel, zo.custom_addr" +
		" from zx_revisit zr" +
		" join zx_order zo on zr.id = zo.revisit_id AND zr.id = " + revisitId

	orm.Eloquent.Raw(selectSql).Scan(&doc)
	fmt.Println(jsoniter.MarshalToString(doc))
	return doc, nil
}

// 获取ZxRevisit带分页
func (e *VRRevisit) GetRevisitPage(pageSize int, pageIndex int) ([]VRRevisit, int, error) {
	var ret []VRRevisit

	selectSql := "SELECT zr.*" +
		", zo.id as order_id, zo.custom_name, zo.custom_tel, zo.custom_addr"
	where := " from zx_revisit zr join zx_order zo on zr.id = zo.revisit_id" +
		" where zo.deleted_at IS NULL"
	if e.CustomName != "" {
		where = fmt.Sprintf("%s AND zo.custom_tel like '%%%s%%'", where, e.CustomName)
	}
	if e.CustomTel != "" {
		where = fmt.Sprintf("%s AND zo.custom_tel = %s", where, e.CustomTel)
	}
	if e.CustomAddr != "" {
		where = fmt.Sprintf("%s AND zo.custom_addr like '%%%s%%'", where, e.CustomAddr)
	}
	if e.RevisiterId == 0 {
		where = fmt.Sprintf(" %s AND (zr.revisiter_id = %s OR zo.create_by = %s)", where, e.CreateBy, e.CreateBy)
	} else {
		where = fmt.Sprintf(" %s AND zr.revisiter_id = %d", where, e.RevisiterId)
	}
	if e.RevisitState != "" {
		where = fmt.Sprintf("%s AND zr.revisit_state = '%s'", where, e.RevisitState)
	}
	var count int
	selectCountSql := "SELECT count(*) " + where
	orm.Eloquent.Raw(selectCountSql).Count(&count)
	pageSql := " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((pageIndex-1)*pageSize)
	selectSql = selectSql + where + pageSql + ";"
	orm.Eloquent.Raw(selectSql).Scan(&ret)
	// 数据权限控制(如果不需要数据权限请将此处去掉)
	//dataPermission := new(DataPermission)
	//dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
	//table, err := dataPermission.GetDataScope(e.TableName(), table)
	//if err != nil {
	//	return nil, 0, err
	//}
	return ret, count, nil
}
